﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Security.AccessControl;
using System.Text;
using System.Windows.Forms;

namespace lgmkr
{
    public class LogMaker
    {
        private string _error;
        private DateTime _errorDateTime;
        private FileStream _fs;
        private List<string> _logText; 

        void CreateOrcheckFolder(string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

        public LogMaker()
        {
            _error = "";
            NowDateTime=DateTime.Now;
            _logText=new List<string>();
            CreateOrcheckFolder(Application.StartupPath + "\\Log");
        }
        public LogMaker(string aError,DateTime nowDateTime)
        {
            _error = aError;
            _errorDateTime = nowDateTime;
            _logText=new List<string>();
            CreateOrcheckFolder(Application.StartupPath+"\\Log");
            //_fs = new FileStream(Application.StartupPath + "\\Log\\log.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }

        public string Error
        {
            get { return _error; } 
            set { _error = value; } 
        }
        public DateTime NowDateTime
        {
            get { return _errorDateTime; }
            set { _errorDateTime = value; }
        }
        public void PrintLog()
        {
            _logText = ReadLog();
            _fs = new FileStream(Application.StartupPath + "\\Log\\log.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
            StreamWriter sw=new StreamWriter(_fs,Encoding.UTF8);
            for (int i = 0; i < _logText.Count;i++ )
            {
                if (i==_logText.Count-1)
                {
                    sw.Write(_logText[i]);
                    continue;
                }
                sw.WriteLine(_logText[i]);
            }
            sw.Write("["+_errorDateTime+"]:"+_error);
            sw.Close();
            _fs.Close();
            _fs.Dispose();
        }
        private List<string> ReadLog()
        {
            var temp=new List<string>();
            _fs = new FileStream(Application.StartupPath + "\\Log\\log.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
            var sr=new StreamReader(_fs,Encoding.UTF8);
            string line;
            do
            {
                line = sr.ReadLine();
                temp.Add(line);
            } 
            while (line != null);
            sr.Close();
            _fs.Close();
            _fs.Dispose();
            return temp;
        }
    }
}
